package com.woniu.controller.component;


import com.woniu.commons.Result;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.util.List;

public abstract class ControllerBase {

    @InitBinder
    public void init(WebDataBinder binder) {

        binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd HH:mm:ss"));
    }


    public Result extractError(BindingResult result) {
        if (result.hasErrors()) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            StringBuilder msgBuilder = new StringBuilder();
            for (FieldError fieldError : fieldErrors) {
                msgBuilder.append(fieldError.getField() + ":" + fieldError.getDefaultMessage() + ";");
            }
            return new Result("400", "fail", null, null);
        }
        return null;
    }

}
